from django.shortcuts import render, HttpResponse

import pymysql

# Create your views here.
# 构造全局空列表，保存参数
num_lyst = []


def info(origin):
    """装饰器函数：在执行视图函数前，完成对输入数值的处理"""

    def inner(request):
        if request.method == 'GET':
            for k, v in request.GET.items():
                param, value_of_param = k, float(v)
                # print("参数>>>", param, "   值", value_of_param)
                # 将参数保存到列表
                num_lyst.append(value_of_param)
        res = origin(request)
        num_lyst.clear()
        # print(num_lyst)
        # num_lyst.clear()
        # print(num_lyst)
        return res

    return inner


def data_add(operand1, operator, operand2, res):
    """
    用来进行数据库交互
    :param result: 运算结果
    :param operand2: 数字2
    :param operand1: 数字1
    :param operator: 运算符名称
    :return: none
    """
    # 连接数据库
    conn = pymysql.connect(host='127.0.0.1', port=3306, user='root', passwd='root', charset='utf8', db='AHU_2021_TEST')
    cursor = conn.cursor()

    sql = f"insert into calc_record(operand1,operator,operand2,result) values({operand1},'{operator}',{operand2},{res})"
    print(sql)
    # 执行SQL语句
    cursor.execute(sql)
    conn.commit()

    # 关闭连接
    cursor.close()
    conn.close()


@info
def add(request):
    """
    加法计算
    :param request:
    :return:res
    """
    res = num_lyst[0] + num_lyst[1]
    data_add(num_lyst[0], "+", num_lyst[1], res)
    return HttpResponse(res)


@info
def multiply(request):
    """
    乘法计算
    :param request:
    :return:
    """
    res = num_lyst[0] * num_lyst[1]
    data_add(num_lyst[0], "*", num_lyst[1], res)
    return HttpResponse(res)


@info
def sub(request):
    """
    减法计算
    :param request:
    :return:
    """
    res = num_lyst[0] - num_lyst[1]
    data_add(num_lyst[0], "-", num_lyst[1], res)
    return HttpResponse(res)


@info
def div(request):
    """
    除法计算
    :param request:
    :return:
    """
    res = num_lyst[0] / num_lyst[1]
    data_add(num_lyst[0], "/", num_lyst[1], res)
    return HttpResponse(res)
